using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

namespace IntelHexConverter
{
	public class IntelHexReader
	{
		List<IntelHexDataSet> 	m_data_sets = new List<IntelHexDataSet>();
		byte[] 			m_byte_data = new byte[0];
		ConversionResult			m_error		= ConversionResult.Unknown;
		
		
		public ConversionResult Read(string filename)
		{
			m_byte_data = new byte[0];
			
			StreamReader fileReader = new StreamReader(filename, Encoding.ASCII);
			
			while(!fileReader.EndOfStream)
			{
				String line = fileReader.ReadLine();	//read one line from the file
				
				IntelHexDataSet dataSet = new IntelHexDataSet(line);
			
				dataSet.ParseLine();
				
				if(dataSet.Result != ConversionResult.OK)
				{
					if(dataSet.Result == ConversionResult.EOF)
					{
						break;
					}
					else
					{
						//an error ocurred
						m_error = dataSet.Result;
						fileReader.Close();
						return dataSet.Result;
					}
				}
				
				m_data_sets.Add(dataSet);
				
			}

			
			fileReader.Close();
			return ConversionResult.OK;
		}
		
		
		public byte[] Data
		{
			get{
				if(m_byte_data.GetLength(0) == 0)
				{
					List<byte> dataTemp = new List<byte>();
					
					for(int count = 0; count<m_data_sets.Count; count++)
					{
						if(m_data_sets[count].Type == 0)
						{
							dataTemp.AddRange(m_data_sets[count].Data);
						}
					}
					
					m_byte_data = dataTemp.ToArray();
				}
				return m_byte_data;
			}
		}
		
		
		//TODO implement segmented data output
		public byte[][] SegmentedData
		{
			get
			{
				throw new NotImplementedException();
			}
		}
		
		
	}
}

